// pages/topicDetail/topicDetail.js
const http = require('../../utils/http.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showText: true,
    details:{},
    dynamicArr:[]
  },
  showAllText() {
    this.setData({
      showText: !this.data.showText
    })
  },
  //参与话题
  canyuTopic(e){
    var item=e.currentTarget.dataset.item;
    wx.setStorageSync('hotTopic', { id: item.id, text: item.topic_name})
    wx.navigateTo({
      url: "/pages/fabudongtai/fabudongtai",
    })
  },
  //点赞
  handleZan(e) {
    var pid = e.currentTarget.dataset.id;
    var uid = app.globalData.uid;
  
    var isZan = e.currentTarget.dataset.zan;
    if (isZan == 1) {
      return wx.showToast({
        title: '您已点过赞了',
        icon: 'none'
      })

    }
    http.fetchApi('procedure_t', { p: `R2017002|${pid}|${uid}` }).then(res => {
      if (res.data.code == 1) {
        if (res.data.results[0].codes == 1) {
          wx.showToast({
            title: '点赞成功',
            icon: 'none'
          })
          var dynamicArr = this.data.dynamicArr;
          dynamicArr.forEach(item => {
            if (item.pid == pid) {
              item.like_num++;
              item.sfdz = 1;
            }
          })
          this.setData({
            dynamicArr
          })

        }
      } else {
        wx.showToast({
          title: '网络繁忙',
          icon: 'none'
        })
      }
    })
  },
  //每进入一次增加一次浏览量
  // addVolume(pid) {
  //   http.fetchApi('procedure_t', { p: `R2017004|${pid}` })
  // },

  //关注
  addFollow() {
    var uid = app.globalData.uid;
    var tid = this.data.details.id
    http.fetchApi('procedure_t', { p: `R2020005|${uid}|${tid}` }).then(res => {
      if (res.data.code == 1) {
        if (res.data.results[0].codes == 1) {
          wx.showToast({
            title: '关注成功'
          })
          setTimeout(() => {
            this.getDetails();
          }, 1000)
        } else if (res.data.results[0].codes == 0) {
          wx.showToast({ title: '不能关注自己!', icon: 'none' })
        }
      }
    })
  },

  //取消关注
  cancelFollow(e) {
    var uid = app.globalData.uid;
    var tid = this.data.details.id
    http.fetchApi('procedure_t', { p: `R2020005|${uid}|${tid}` }).then(res => {
      if (res.data.code == 1) {
        wx.showToast({
          title: '取消关注',
        })
        setTimeout(() => {
          this.getDetails();
        }, 1000)
      }
    })
  },

  //话题详情
  getDetails(){
    var uid=app.globalData.uid;
    http.fetchApi('procedure_t', { p: `R2020002|${uid}|${this.data.tid}` }).then(res=>{
      if(res.data.code==1){
        var details = res.data.results[0];
        this.setData({
          details
        })
      }
    })
  },
  //图片预览
  previewImg(e) {
    var imgs = e.currentTarget.dataset.imgs,
      img = e.currentTarget.dataset.img;
    console.log(imgs, img)
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },

  toDetails(e) {
    var pid = e.currentTarget.dataset.pid;
    wx.navigateTo({
      url: "/pages/dynamicDetail/dynamicDetail?pid=" + pid + '&type=1' 
    })
  },

//收藏
  collection(e){
    var uid = app.globalData.uid;
    var pid=e.currentTarget.dataset.id;
    http.fetchApi('procedure_t', { p: `R2018002|${uid}|${pid}` }).then(res=>{
      if(res.data.code==1){
        if (res.data.results[0].codes==1){
          wx.showToast({
            title: '收藏成功',
          })
        }else{
          wx.showToast({title: '网络繁忙',icon:'none'})
        }
      }else{
        wx.showToast({ title: '网络繁忙', icon: 'none' })
      }
    })
  },
  //获取热门讨论
  getHotDynamic(page) {
    wx.showLoading({
      title: '加载中',
    })
    var uid = app.globalData.uid;
    var current = this.data.current;
        var params = {
          p: 'R1001010',
          k: page,
          j: 10,
          cs: `0|${uid}|${this.data.tid}|0|0`
        }
    console.log(`0|${uid}|${this.data.tid}|0|0`)
        http.fetchApi('procedureList', params).then(ret => {
          wx.hideLoading();
          var { code, results } = ret.data;
          // console.log(code, results)
          if (code == 1) {
            var dynamicArr = this.data.dynamicArr;
            var dynamicArr1 = results;
            if (page == 1) {
              dynamicArr = results;
            } else {
              dynamicArr = [...dynamicArr, ...dynamicArr1]
            }
           
            this.setData({
              dynamicArr,
              page,
              pageNum: dynamicArr1.length
            })
          }
        })
    

  },
  //取消分享按钮的冒泡事件
  fn() {
    // console.log(666)
  },

  emoji2Str(str) {

    return unescape(escape(str).replace(/\%uD.{3}/g, ''));

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var tid=options.tid;
    this.setData({
      tid
    })

    // 分享进来时获取uid
    if (app.globalData.uid) {
      // this.addVolume(tid);
      this.getDetails();
      this.getHotDynamic(1);
    } else {
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.userInfo']) {
            wx.showModal({
              title: '提示',
              content: '您还没有授权,请开启授权',
              confirmColor: '#0DCF92',
              success(ret) {
                if (ret.confirm) {
                  wx.reLaunch({
                    url: '/pages/index/index',
                  })
                } else if (ret.cancel) {

                }
              }
            })

          } else {
            wx.getUserInfo({
              success: results => {
                app.globalData.userInfo = results.userInfo
                console.log(app.globalData.userInfo);

                wx.login({
                  success: (res2) => {

                    if (res2.code) {
                      var url;
                      const yxhj = wx.getSystemInfoSync();
                      console.log(yxhj.AppPlatform)
                      app.globalData.cj = yxhj.AppPlatform
                      if (yxhj.AppPlatform == 'qq') {
                        url = app.globalData.host + 'qqApi/login'
                      } else {
                        url = app.globalData.host + 'api/login'
                      }
                      wx.request({
                        url,
                        method: 'get',
                        header: {
                          "Content-Type": "applciation/json"
                        },
                        // data: { encryptedData: results.encryptedData, iv: results.iv, code: res.code },
                        data: { avatarUrl: results.userInfo.avatarUrl, nickName: this.emoji2Str(results.userInfo.nickName), code: res2.code },
                        success: (result) => {
                          if (result.data.code == 1) {

                            app.globalData.token = result.data.accesstoken;
                            //uid保存全局
                            app.globalData.uid = result.data.uid;
                            // this.addVolume(tid);
                            this.getDetails();
                            this.getHotDynamic(1);
                          } else {
                            wx.showToast({
                              title: '网络繁忙',
                              icon: 'none'
                            })

                          }

                        }
                      })


                    } else {
                      console.log('网络繁忙' + res.errMsg)
                    }
                  }
                })

              }
            })
          }
        }
      })
    }


    // this.addVolume(tid);
    // this.getDetails();
    // this.getHotDynamic(1);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var query = wx.createSelectorQuery();
    setTimeout(() => {
      query.select('.dynamics-text').boundingClientRect();
    }, 1000)
    console.log(query.select('.dynamics-text'))
    query.exec((res) => {
      console.log(res)
      res[0].height;
      console.log("height==", res[0].height)
      var height = res[0].height;
      //20为css里设置的view的line-height
      this.data.colNum = height / 20;
      console.log("行数==", this.data.colNum)
      if (height > 60) {
        this.setData({
          colNum: this.data.colNum,
          showText: false
        })
        return
      }
      this.setData({
        colNum: this.data.colNum,
      })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
   
    var page = this.data.page || 1;
    page++;
    if (this.data.pageNum < 10) {
      http.showToast('暂无更多!' + '', '', 'none')
      return
    }
    this.getHotDynamic(page);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var pid = res.target.dataset.id;
    var uid = app.globalData.uid;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      http.fetchApi('procedure_t', { p: `R2017005|${pid}|${uid}` }).then(req => {
        if (req.data.code == 1) {
          if (req.data.results[0].codes == 1) {
            var dynamicArr = this.data.dynamicArr;
            dynamicArr.forEach(item => {
              if (item.pid == pid) {
                item.fenxiang_num++;

              }
            })
            this.setData({
              dynamicArr
            })
          }
        }
      })
    }
    return {
      // title: '自定义转发标题',
      path: '/pages/dynamicDetail/dynamicDetail?pid=' + pid + '&type=1' + '&shared=1'
    }
  }
})